package com.common.database.config;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

/**
 * @author 24373
 * @description
 * @date 2024/3/20 22:09
 */
@Configuration
@EnableAutoConfiguration
@MapperScan(basePackages = "com.*.db1.*.mapper", sqlSessionTemplateRef = "test1SessionFactory")
public class Db1DataConfig {
    @Bean
    @ConfigurationProperties("com.datasource.db1")
    public HikariConfig db1DataSourceConfig() {
        HikariConfig hikariConfig = new HikariConfig();
        return hikariConfig;
    }

    @Bean("db1DataSource")
    public DataSource db1DataSource() {
        return new HikariDataSource(db1DataSourceConfig());
    }

    @Bean("db1SessionFactory")
    public SqlSessionFactory db1SessionFactory(@Qualifier("db1DataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/db1/*.xml"));
        return sqlSessionFactoryBean.getObject();
    }

    @Bean("db1SessionFactory")
    public SqlSessionTemplate db1SessionFactory(SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

}
